package interceptor

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo/v4"
	"net/http"
	"note/service/util"
	"strings"
)

func JWT() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			var code int
			var data interface{}

			code = util.SUCCESS
			Authorization := c.Request().Header.Get(("Authorization"))
			token := strings.Split(Authorization, " ")

			if Authorization == "" {
				code = util.INVALID_PARAMS
			} else {
				_, err := util.ParseToken(token[0])
				if err != nil {
					switch err.(*jwt.ValidationError).Errors {
					case jwt.ValidationErrorExpired:
						code = util.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
					default:
						code = util.ERROR_AUTH_CHECK_TOKEN_FAIL
					}
				}
			}
			if code != util.SUCCESS {
				return c.JSON(http.StatusUnauthorized, map[string]interface{}{
					"code": code,
					"msg":  util.GetMsg(code),
					"data": data,
				})
			}
			return next(c)
		}
	}
}
